package com.spring.theory.bean.lifeCycle;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * bean生命周期中模板方法的运用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-07-05 17:59
 */
@Slf4j
public class TemplateBean {

    public static void main(String[] args) {
        TestBean testBean = new TestBean();
        testBean.addProcess(new TestBeanPostProcessor() {
            @Override
            public void inject() {
                log.info("@Autowire方法");
            }
        });
        testBean.addProcess(new TestBeanPostProcessor() {
            @Override
            public void inject() {
                log.info("@Resource方法");
            }
        });
        testBean.process();
    }

    static class TestBean {

        /**
         * bean的生命周期是固定不动的模板；而需要扩展的部分是变化的
         */
        public Object process() {
            Object obj = new Object();
            log.info("1.实例化");
            log.info("2.依赖注入");
            log.info("3.初始化");
            /**
             * 模板固定不动；给变化的部分开个口子，用接口做
             */
            for (TestBeanPostProcessor processor : processorList) {
                processor.inject();
            }
            log.info("4.销毁");
            return obj;
        }

        static final List<TestBeanPostProcessor> processorList = new ArrayList<>();

        public void addProcess(TestBeanPostProcessor bean) {
            processorList.add(bean);
        }

    }

    static interface TestBeanPostProcessor {
        void inject();
    }

}
